package com.zzb.codegenerator;

import com.zzb.codegenerator.bean.ProjectMeta;
import com.zzb.codegenerator.config.GeneratorConfig;
import com.zzb.codegenerator.config.GeneratorConfigPropertiesFactory;
import com.zzb.codegenerator.generator.FreeMarkerGenerator;
import com.zzb.codegenerator.generator.IGenerator;
import com.zzb.codegenerator.generator.connect.ConnectPool;
import com.zzb.codegenerator.generator.dctm.hive.HiveToTableMetaConvertor;
import com.zzb.codegenerator.generator.dctm.mysql.MysqlDbToTableMetaConvertor;
import com.zzb.codegenerator.generator.dctm.postgresql.PostgresqlDbToTableMetaConvertor;
import com.zzb.codegenerator.generator.dctm.sqlserver.SQLServerToTableMetaConvertor;
import com.zzb.codegenerator.generator.table.ITableMetaFoctory;
import com.zzb.codegenerator.utils.GetJdbcUrlUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * 主程序
 * Created by zhangzhenbin on 2016/9/30.
 */
public class Main {
    public static void main(String[] args) {
        try {
            //生成配置类
            String propertiesFile = "default.properties";
            if(ArrayUtils.isNotEmpty(args)){
                propertiesFile = args[0];
            }
            GeneratorConfig config = new GeneratorConfigPropertiesFactory().build(propertiesFile);
            String driverClassName = GetJdbcUrlUtil.getDriverName(config.getJdbcUrl());
            //获取tableMeta列表
            List<ProjectMeta> projectMetaList = null;
            if (driverClassName.equals("org.postgresql.Driver")) {
                projectMetaList= new ITableMetaFoctory(new PostgresqlDbToTableMetaConvertor(config)).createProjectMetaList(config);
            } else if(driverClassName.equals("net.sourceforge.jtds.jdbc.Driver")){
                projectMetaList= new ITableMetaFoctory(new SQLServerToTableMetaConvertor(config)).createProjectMetaList(config);
            } else if(driverClassName.equals("org.apache.hive.jdbc.HiveDriver")){
                projectMetaList = new ITableMetaFoctory(new HiveToTableMetaConvertor(config)).createProjectMetaList(config);
            } else {
                projectMetaList= new ITableMetaFoctory(new MysqlDbToTableMetaConvertor(config)).createProjectMetaList(config);
            }
            //执行生成方法
            IGenerator iGenerator = null;
            if("freemarker".equals(config.getTemplateType()) || StringUtils.isBlank(config.getTemplateType())){
                iGenerator = new FreeMarkerGenerator();
            }
            if(iGenerator == null){
                throw new Exception("请选择模板类型，现在支持freemarker");
            }
            iGenerator.generator(config,projectMetaList);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ConnectPool.closeAll();
        }
    }
}
